package com.wzp.weiliao.service.imp;

import com.wzp.weiliao.enmus.MsgSignFlagEnum;
import com.wzp.weiliao.enmus.SearchFriendsStatusEnum;
import com.wzp.weiliao.mapper.*;
import com.wzp.weiliao.netty.ChatMsg;

import com.wzp.weiliao.entity.FriendsRequest;
import com.wzp.weiliao.entity.MyFriends;
import com.wzp.weiliao.entity.Users;
import com.wzp.weiliao.entity.vo.FriendRequestVo;
import com.wzp.weiliao.entity.vo.MyFriendsVo;
import com.wzp.weiliao.service.Userservice;
import com.wzp.weiliao.utils.FastDFSClient;
import com.wzp.weiliao.utils.FileUtils;
import com.wzp.weiliao.utils.JsonUtils;
import com.wzp.weiliao.utils.QRCodeUtils;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;


import java.util.Date;
import java.util.List;

/**
 * @author 王振鹏
 * @version 1.0
 * @date 2019/8/8 15:17
 * @Description: 用户service实现类
 */
@Service
public class UserserviceImp implements Userservice {
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private MyFriendsMapper myFriendsMapper;
    @Autowired
    private UsersMapperCustom usersMapperCustom;
    @Autowired
    private FriendsRequestMapper friendsRequestMapper;
    @Autowired
    private Sid sid;
    @Autowired

    private ChatMsgMapper chatMsgMapper;
    @Autowired
    private QRCodeUtils qrCodeUtils;
    @Autowired
    private FastDFSClient fastDFSClient;
//   @Transactional(propagation = Propagation.REQUIRED)事务注解
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean queryUsernameIsExist(String username) {
        Users users = new Users();
        users.setUsername(username);
        Users result = usersMapper.selectOne(users);
        return result !=null?true:false;

    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users queryUserForLogin(String username, String pwd) {
//      Example：逆向工程工具类
        Example userExample = new Example(Users.class);
        Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("username",username);
        criteria.andEqualTo("password",pwd);
        Users result = usersMapper.selectOneByExample(userExample);

        return result;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users saveUser(Users user) {

       String userId = sid.nextShort();

        // 为每个用户生成一个唯一的二维码
        //还可以加密解密
        String qrCodePath = "C:/img"+"/userqrcode" + userId + "qrcode.png";
        // muxin_qrcode:[username]
        qrCodeUtils.createQRCode(qrCodePath,"muxin_qrcode:"+user.getUsername());
        // 上传文件到fastdfs
        MultipartFile qrCodeFile = FileUtils.fileToMultipart(qrCodePath);

        String qrCodeUrl = "";

        try {
            qrCodeUrl = fastDFSClient.uploadQRCode(qrCodeFile);
        }catch ( Exception e){
            e.printStackTrace();
        }

        user.setQrcode(qrCodeUrl);
        user.setId(userId);

        usersMapper.insert(user);
        return user;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users updateUserInfo(Users user) {

       usersMapper.updateByPrimaryKeySelective(user);

        return queryUserById(user.getId());
    }
    @Transactional(propagation = Propagation.REQUIRED)

    public Users queryUserById(String userId) {

        return usersMapper.selectByPrimaryKey(userId);


    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Integer preconditionSearchFriends(String myUserId, String friendUsername) {

        System.out.println("测试1"+myUserId);
        System.out.println("测试2"+friendUsername);
        Users users = queryUserInfoByUsername(friendUsername);

        //1. 搜索的用户如果不存在，返回[无此用户]
        if (users == null){
            return SearchFriendsStatusEnum.USER_NOT_EXIST.status;
        }
        //2.搜索账号是你自己，返回[不能添加自己]

        if (users.getId().equals(myUserId)){
            return SearchFriendsStatusEnum.NOT_YOURSELF.status;
        }
        //3. 搜索的朋友已经是你的好友，返回[该用户已经是你的好友]
        Example myfriend = new Example(MyFriends.class);
        Criteria userCriteria= myfriend.createCriteria();
        userCriteria.andEqualTo("myUserId",myUserId);
        userCriteria.andEqualTo("myFriendUserId",users.getId());
        MyFriends myFriendsRel =  myFriendsMapper.selectOneByExample(myfriend);
        if (myFriendsRel != null){
            return SearchFriendsStatusEnum.ALREADY_FRIENDS.status;
        }
        return SearchFriendsStatusEnum.SUCCESS.status;

    }

    @Override
    public Users queryUserInfoByUsername(String username) {
        Example user = new Example(Users.class);
        Criteria userCriteria= user.createCriteria();
        userCriteria.andEqualTo("username",username);

        return  usersMapper.selectOneByExample(user);


    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void sendFriendRequest(String myUserId, String friendUsername) {
        // 根据用户名把朋友信息查询出来
         Users friend = queryUserInfoByUsername(friendUsername);
        // 1. 查询发送好友请求记录表
        Example friends = new Example(FriendsRequest.class);
        Criteria friendCriteria= friends.createCriteria();
        friendCriteria.andEqualTo("sendUserId", myUserId);
        friendCriteria.andEqualTo("acceptUserId", friend.getId());
        FriendsRequest friendRequest = friendsRequestMapper.selectOneByExample(friends);
        if (friendRequest == null) {
            // 2. 如果不是你的好友，并且好友记录没有添加，则新增好友请求记录
            //生成唯一id
            String requestId = sid.nextShort();

            FriendsRequest friendsRequest = new FriendsRequest();
            friendsRequest.setId(requestId);
            friendsRequest.setSendUserId(myUserId);
            friendsRequest.setAcceptUserId(friend.getId());
            friendsRequest.setRequestDateTime(new Date());
            friendsRequestMapper.insert(friendsRequest);

        }

    }
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<FriendRequestVo> queryFriendRequestList(String acceptUserId) {
        return usersMapperCustom.queryFriendRequestList(acceptUserId);
    }

    @Override
    public void deleteFriendRequest(String sendUserId, String acceptUserId) {
        Example friends = new Example(FriendsRequest.class);
        Criteria friendCriteria= friends.createCriteria();
        friendCriteria.andEqualTo("sendUserId", sendUserId);
        friendCriteria.andEqualTo("acceptUserId", acceptUserId);
        friendsRequestMapper.deleteByExample(friends);

    }
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void passFriendRequest(String sendUserId, String acceptUserId) {

        saveFriends(sendUserId, acceptUserId);
        //逆向保存
        saveFriends(acceptUserId, sendUserId);
        deleteFriendRequest(sendUserId, acceptUserId);

//        Channel sendChannel = UserChannelRel.get(sendUserId);
//        if (sendChannel != null) {
//            // 使用websocket主动推送消息到请求发起者，更新他的通讯录列表为最新
//            DataContent dataContent = new DataContent();
//            dataContent.setAction(MsgActionEnum.PULL_FRIEND.type);
//
//            sendChannel.writeAndFlush(
//                    new TextWebSocketFrame(
//                            JsonUtils.objectToJson(dataContent)));
//        }


    }
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveFriends(String sendUserId, String acceptUserId) {
        MyFriends myFriends = new MyFriends();
        String recordId = sid.nextShort();
        myFriends.setId(recordId);
        myFriends.setMyFriendUserId(acceptUserId);
        myFriends.setMyUserId(sendUserId);
        myFriendsMapper.insert(myFriends);
    }
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<MyFriendsVo> queryMyFriends(String userId) {
        List<MyFriendsVo> myFirends = usersMapperCustom.queryMyFriends(userId);
        return myFirends;
    }

    @Transactional(propagation = Propagation.SUPPORTS) @Override
    public String saveMsg(ChatMsg chatMsg) {
       com.wzp.weiliao.entity.ChatMsg msgDB = new com.wzp.weiliao.entity.ChatMsg();
        String msgId = sid.nextShort();
        msgDB.setId(msgId);
        msgDB.setAcceptUserId(chatMsg.getReceiverId());
        msgDB.setSendUserId(chatMsg.getSenderId());
        msgDB.setCreateTime(new Date());
        msgDB.setSignFlag(MsgSignFlagEnum.unsign.type);
        msgDB.setMsg(chatMsg.getMsg());

        chatMsgMapper.insert(msgDB);

        return msgId;
    }

    @Override
    public void updateMsgSigned(List<String> msgIdList) {
         usersMapperCustom.batchUpdateMsgSigned(msgIdList);
    }

    @Override
    public List<ChatMsg> getUnReadMsgList(String acceptUserId) {
        return null;
    }
}
